<?php

namespace app\api\controller;

use app\api\model\Eggs as EggsDB;
use Illuminate\Support\Carbon;
use support\Request;
use app\traits\GameBowl;
use app\api\model\Wallets as WalletsDB;
use app\api\model\GameBowl as GameBowlDB;
use app\api\model\GameBowlPlayers as GameBowlPlayersDB;
use app\api\model\UserUseEggs as UserUseEggsDB;
use app\api\model\AdminConfigs as AdminConfigsDB;

//聚宝盆游戏
class GameBowlController
{
    use GameBowl;

    public function add()
    {
        $req = [];
        $req['date_id'] = date("YmdHi");
//        $req['week'] = date("w");
        //测试循环周一到周天
        $per = GameBowlDB::orderBy('id', 'desc')->first();
        if ($per == null || $per['week'] == 7) {
            $req['week'] = 1;
        } else {
            $req['week'] = $per['week'] + 1;
        }
        //测试循环周一到周天
        $req['created_at'] = Carbon::now()->toDateTimeString();
        $req['stop_time'] = Carbon::now()->addMinutes(4)->toDateTimeString();
        $req['percent'] = AdminConfigsDB::where('id', 2)->value('pot_daily_commission_rate');
        $req['pot_next_rate'] = AdminConfigsDB::where('id', 2)->value('pot_next_rate');

        if ($req['week'] == 1) {
            $req['total'] = 0;
            //pot_next_rate
        } else if ($req['week'] == 7) {
            $req['percent'] = 0;
        }
        $s1 = $req;
        $s2 = $req;
        $s3 = $req;
        if ($req['week'] != 1) {
            $r1 = GameBowlDB::where('type', 1)->orderBy('id', 'desc')->first();
            $s1['total'] = $r1['yue'];
            $r2 = GameBowlDB::where('type', 2)->orderBy('id', 'desc')->first();
            $s2['total'] = $r2['yue'];
            $r3 = GameBowlDB::where('type', 3)->orderBy('id', 'desc')->first();
            $s3['total'] = $r3['yue'];
        }
        $s1['type'] = 1;
        $s2['type'] = 2;
        $s3['type'] = 3;
        $res = GameBowlDB::insert([$s1, $s2, $s3]);
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    public function list()
    {
        $res = GameBowlDB::orderBy('id', 'desc')->paginate(10);
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    //开奖
    public function openGame()
    {
//        $type = $request->post('type');
        $res[1]= $this->openGameF(1);
        $res[2]= $this->openGameF(2);
        $res[3]= $this->openGameF(3);
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    public function openGameF($type)
    {
        //当前游戏期次数据
        $r = GameBowlDB::where('type', $type)->orderBy('id', 'desc')->first();
        //获取投注次数
        $count_db = AdminConfigsDB::where('id', 2)->value('lottery_winner_num');
        $count = GameBowlPlayersDB::where('type', $type)->where('date_id', $r['date_id'])->count();
        if ($count_db >= $count) {
            $yue = GameBowlDB::where('id', $r['id'])->value('total') - GameBowlPlayersDB::where('type', $type)->where('date_id', $r['date_id'])->sum('count');
            GameBowlDB::where('type', $type)->where('id', $r['id'])->update([
                'yue' => $yue,
            ]);
            //更新中奖状态为退奖
            GameBowlPlayersDB::where('type', $type)->where('date_id', $r['date_id'])->update(['is_got' => 2]);

            //获取所有投注信息
            $vs= GameBowlPlayersDB::where('type', $type)->where('date_id', $r['date_id'])->get()->toArray();
            foreach ($vs as $v){
                $held_eggs = WalletsDB::where('wallet_user_id',  $v['user_id'])->value("held_eggs");
                //给钱包退钱
                WalletsDB::where('wallet_user_id', $v['user_id'])->update([
                    'held_eggs' => $v['count']  + $held_eggs
                ]);
                //添加U蛋记录
                EggsDB::insertGetId([
                    'uid' => $v['user_id'],
                    'count' => $v['count'],
                    'type' => '游戏-退还本金-聚宝盆'.$v['date_id'],
                    'yu_e'=> $v['count']  + $held_eggs,
                    'created_at' => Carbon::now()->toDateTimeString()
                ]);
            }
        }
        //获取奖金池金额
        $total = GameBowlDB::where('id', $r['id'])->value('total');
        $percent = GameBowlDB::where('id', $r['id'])->value('percent');
        $pot_next_rate = GameBowlDB::where('id', $r['id'])->value('pot_next_rate');
        $yue1 = $total * ($pot_next_rate / 100);   //平台扣除的
        $yue = $total * ($percent / 100);      //下一期的余额
        $price = ($total - $yue1 -$yue) / $count_db;
        //获取中奖投注信息
        $list = GameBowlPlayersDB::where('type', $type)->where('date_id', $r['date_id'])->inRandomOrder()->limit($count_db)->get()->toArray();
        $winner = [];
        //更新中奖信息
        foreach ($list as $k => $v) {
            $list[$k]['is_got'] = 1;
            $list[$k]['price'] = $price;
            $winner[$k] = $list[$k]['id'];
        }
        GameBowlPlayersDB::where('type', $type)->where('date_id', $r['date_id'])->upsert(
            $list,
            ['id'],
            ['is_got', 'price']
        );
        $vs = $list;
        foreach ($vs as $v){
            if($v['is_got']==1){
                //给钱包加上中奖金额和本金
                $held_eggs = WalletsDB::where('wallet_user_id',$v['user_id'])->value('held_eggs');
                WalletsDB::where('wallet_user_id',$v['user_id'])->update([
                    'held_eggs'=> $v['price']+$held_eggs
                ]);
                //添加U蛋记录
                EggsDB::insertGetId([
                    'uid' => $v['user_id'],
                    'count' => $v['price'],
                    'type' => '游戏-中奖-聚宝盆'.$v['date_id'],
                    'yu_e'=>$v['price']+$held_eggs,
                    'created_at' => Carbon::now()->toDateTimeString()
                ]);
            }
        }
        GameBowlDB::where('type', $type)->where('id', $r['id'])->update([
            'yue' => $yue,
            'winner' => json_encode($winner)
        ]);
        $res = GameBowlPlayersDB::where('type', $type)->where('date_id', $r['date_id'])->where('is_got', 1)->get();
        return $res;
    }

    //获取当天游戏
    public function getNowGame()
    {
        $res[0] = GameBowlDB::where('type', 1)->orderBy('id', 'desc')->first();
        $res[1] = GameBowlDB::where('type', 2)->orderBy('id', 'desc')->first();
        $res[2] = GameBowlDB::where('type', 3)->orderBy('id', 'desc')->first();
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }
    //用户操作
    //押注
    public function playGame(Request $request)
    {
        $req = [];
        //获取用户id
        $uid = $request->uid;
        $req['user_id'] = $request->uid;
        $req['count'] = $request->post('count');
        $req['type'] = $request->post('type');
        $req['created_at'] = Carbon::now()->toDateTimeString();
        $id = $request->post('id');
        //判断是否暂停投注
        $r = GameBowlDB::where('id', $id)->first();
        $req['date_id'] = $r['date_id'];
        $stop_time = Carbon::createFromFormat('Y-m-d H:i:s', $r['stop_time']);
        $now_time = Carbon::now();
        if ($now_time->gte($stop_time)) {
            return json([
                'code' => 0,
                'msg' => 'ok',
                'data' => '已经停止祈福',
            ]);
        }


        //判断当前是否有count 202405061005
        $count_db = WalletsDB::where('wallet_user_id', $uid)->value("held_eggs");
        if ($req['count'] < $count_db) {
            $res = GameBowlPlayersDB::insertGetId($req);
            WalletsDB::where('wallet_user_id', $uid)->update([
                "held_eggs" => $count_db - $req['count'],
                "used_eggs" => WalletsDB::where('wallet_user_id', $uid)->value("used_eggs") + $req['count']
            ]);
            //添加到奖金池
            $total = GameBowlDB::where('id', $id)->value('total');
            GameBowlDB::where('id', $id)->update([
                'total' => $total + $req['count']
            ]);
//            UserUseEggsDB::insertGetId([
//                'user_id'=>$uid,
//                'count'=>$req['count'],
//                'use_type'=>'游戏-聚宝盆'.$req['type'].'-投注',
//                'type'=>0,
//                'created_at'=> Carbon::now()->toDateTimeString()
//            ]);
            //添加U蛋记录
            EggsDB::insertGetId([
                'uid' => $uid,
                'count' => $req['count'],
                'type' => '游戏-竞猜-聚宝盆'.$req['date_id'],
                'yu_e'=>$count_db - $req['count'],
                'created_at' => Carbon::now()->toDateTimeString()
            ]);
        } else {
            return json([
                'code' => 0,
                'msg' => 'ok',
                'data' => 'U蛋不够',
            ]);
        }
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    //押注列表
    public function playGameList(Request $request)
    {
        $uid = $request->uid;
        $list = GameBowlPlayersDB::where('user_id', $uid)->orderBy('id', 'desc')->paginate(10);
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $list,
        ]);
    }

    //兑奖
    public function gotPrize(Request $request)
    {
        $uid = $request->uid;
        $id = $request->post('id');
        $info = GameBowlPlayersDB::where('id', $id)->first();
        if ($info['is_got'] !== 0 && $info['is_dui'] == 0) {
            //更新用户列表
            GameBowlPlayersDB::where('id', $id)->update([
                'is_dui' => 1
            ]);
            //更新用户钱包中奖额
            $held_eggs = WalletsDB::where('wallet_user_id', $uid)->value('held_eggs');

            if($info['is_got'] == 1){
                $res = WalletsDB::where('wallet_user_id', $uid)->update([
                    'held_eggs' => $info['price']  + $held_eggs
                ]);
//                UserUseEggsDB::insertGetId([
//                    'user_id'=>$uid,
//                    'count'=>$info['price'],
//                    'use_type'=>'游戏-聚宝盆'.$info['type'].'-中奖',
//                    'type'=>1,
//                    'created_at'=> Carbon::now()->toDateTimeString()
//                ]);
            }

            if($info['is_got'] == 2){
                $res = WalletsDB::where('wallet_user_id', $uid)->update([
                    'held_eggs' => $info['count']  + $held_eggs
                ]);
//                UserUseEggsDB::insertGetId([
//                    'user_id'=>$uid,
//                    'count'=>$info['count'],
//                    'use_type'=>'游戏-聚宝盆'.$info['type'].'-退还本金',
//                    'type'=>1,
//                    'created_at'=> Carbon::now()->toDateTimeString()
//                ]);
            }
            return json([
                'code' => 2,
                'msg' => 'ok',
                'data' => $res,
            ]);
        } else if ($info['is_got'] !== 0 && $info['is_dui'] == 1) {
            return json([
                'code' => 4,
                'msg' => 'ok',
                'data' => '已经兑过了',
            ]);
        } else {
            return json([
                'code' => 4,
                'msg' => 'ok',
                'data' => '没有中奖',
            ]);
        }
    }

    //获取中奖信息
    public function gotPriceList(Request $request)
    {
        $date_id = $request->get('date_id');
        $list['one'] = GameBowlPlayersDB::where('date_id', $date_id)->where('type', 1)->where('is_got', 1)
            ->join('user_logins', 'game_bowl_players.user_id', '=', 'user_logins.uid')
            ->select('game_bowl_players.*', 'user_logins.phone_number')->get();
        $list['two'] = GameBowlPlayersDB::where('date_id', $date_id)->where('type', 2)->where('is_got', 1)
            ->join('user_logins', 'game_bowl_players.user_id', '=', 'user_logins.uid')
            ->select('game_bowl_players.*', 'user_logins.phone_number')->get();
        $list['three'] = GameBowlPlayersDB::where('date_id', $date_id)->where('type', 3)->where('is_got', 1)
            ->join('user_logins', 'game_bowl_players.user_id', '=', 'user_logins.uid')
            ->select('game_bowl_players.*', 'user_logins.phone_number')->get();
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $list,
        ]);
    }

    //获取往期期号
    public function historyDateId()
    {
        $list = GameBowlDB::distinct()->orderBy('date_id', 'desc')->pluck('date_id');
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $list,
        ]);
    }

}
